package io.babystar.modules.business.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import io.babystar.common.utils.DateUtils;
import io.babystar.modules.business.entity.*;
import io.babystar.modules.business.service.*;
import io.babystar.modules.sys.controller.AbstractController;
import io.babystar.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import io.babystar.common.utils.PageUtils;
import io.babystar.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;


/**
 *
 *
 * @author jeson
 * @email 574197743@qq.com
 * @date 2021-03-23 20:03:33
 */
@RestController
@RequestMapping("business/student")
public class StudentController extends AbstractController {

    @Autowired
    private SignService signService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private ParentService parentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private CourseDateService courseDateService;
    @Autowired
    private CourseStudentService courseStudentService;
    @Autowired
    private StudentCourseDateService studentCourseDateService;
    @Autowired
    private CWOrderService cwOrderService;

    /**
     * 后台签到
     * @param studentId
     * @param cdId
     * @return
     */
    @GetMapping("/signInBybackstage")
    @ApiOperation("后台签到")
    public R signInBybackstage(String studentId,String cdId,String teacherId,String teacherName, String signTime) {
        try{
            if(StringUtils.isEmpty(teacherId) || StringUtils.isEmpty(teacherName)){
                return R.error("签到老师不能为空！");
            }
            SysUserEntity user = this.getUser();
            CourseDateEntity cdEntity =  courseDateService.getById(cdId);
            StudentCourseDateEntity scdEntity = new StudentCourseDateEntity();
            SignEntity t = new SignEntity();
            t.setStudentId(Integer.parseInt(studentId));
            t.setCourseId(cdEntity.getCourseId());
            t.setTeacherId(Integer.parseInt(teacherId));
            t.setTeacherName(teacherName);

            String courseWeekZh = cdEntity.getCourseWeekZh();
            String nowWeekZh = DateUtils.dateToWeek(signTime);
            if(!courseWeekZh.equals(nowWeekZh)){
                return R.error("课程与签到时间不匹配！");
            }

            t.setSignTime(DateUtils.stringToDate(signTime,DateUtils.DATE_TIME_PATTERN));
            t.setCourseTimeId(Integer.parseInt(cdId));
            t.setCourseTimeDesc(signTime.substring(0,10)+" "+courseWeekZh);
            //后台签到
            t.setSource("3");
            //设置机构
            t.setBusinessId(Integer.parseInt( user.getBusinessId()+""));
            scdEntity.setCourseId(cdEntity.getCourseId());
            scdEntity.setCourseTimeId(Integer.parseInt(cdId));
            scdEntity.setStudentId(Integer.parseInt(studentId));
            boolean sign = signService.signInBybackstage(t,scdEntity);
            if(sign){
                return R.ok();
            }else {
                return R.error("签到失败，没有剩余课时");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:student:list")
    public R list(@RequestParam Map<String, Object> params){
        System.out.println(params);
        PageUtils page = null;
        try {
            SysUserEntity user = this.getUser();
            if(user.getBusinessId()==null){
                return R.error("没有分配机构代码，请联系管理员");
            }
            params.put("organizeid", user.getBusinessId());
            page = studentService.queryPageStudent(params);
            System.out.println("看看学生控制层的page打印出来没有"+page.getList()+page.getCurrPage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("page", page);
    }


        /**
         * 信息
         */
        @GetMapping("/info/{id}")
        @RequiresPermissions("business:student:info")
        public R info(@PathVariable("id") Integer id){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		StudentEntity student = studentService.getById(id);
		ParentEntity parent = parentService.getById(student.getParentId());
		StudentEntityAll studentEntityAll = new StudentEntityAll();
		studentEntityAll.setId(Long.parseLong(student.getId()+""));
		studentEntityAll.setStudentname(student.getStudentName());
        if(student.getStudentAge()!=null){
            studentEntityAll.setStudentage(sdf.format(student.getStudentAge()));
        }
		studentEntityAll.setRefereename(parent.getRefereeName());
		studentEntityAll.setStudentmather(parent.getParentName());
		studentEntityAll.setMatherphone(parent.getParentPhone());
		studentEntityAll.setOther(parent.getOther());
		studentEntityAll.setOtherphone(parent.getOtherPhone());
        studentEntityAll.setSchool(student.getSchool());
        studentEntityAll.setAddress(student.getAddress());
        studentEntityAll.setCardtype(student.getCardTypeId());
        studentEntityAll.setGiftequipment(student.getEquipment());
        studentEntityAll.setDuetime(student.getDueTime());
        studentEntityAll.setPayment(student.getPayment());
        studentEntityAll.setResidualclasshour(student.getResidualClassHour());
        studentEntityAll.setClassPeriod(student.getClassPeriod());
        studentEntityAll.setShopid(student.getShopId());
        studentEntityAll.setRemark(student.getRemark());
        studentEntityAll.setConsultant(student.getConsultant());
        studentEntityAll.setWeekLimit(student.getWeekLimit());
        studentEntityAll.setCreatetime(student.getCreateTime());
        return R.ok().put("student", studentEntityAll);
    }

    /**
     * 保存
     */
    @Transactional
    @RequestMapping("/save")
    @RequiresPermissions("business:student:save")
    public R save(@RequestBody StudentEntityAll student) {
        //String salt = "XicP18901KbQu6mQ7AZk";
        try {
            /*if (student.getPassword() != null) {
                student.setPassword(new Sha256Hash(student.getPassword(), salt).toHex());
            }*/
            Map<String,String> result = studentService.saveStudent(student, this.getUser());
            String code = result.get("code");
            if("0".equals(code)){
                return R.ok();
            }else{
                return R.error(result.get("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RequiresPermissions("business:student:update")
    public R update(@RequestBody StudentEntityAll student){
        try{
            studentService.updateStudent(student);
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @RequiresPermissions("business:student:delete")
    public R delete(@RequestBody Integer[] ids){
		studentService.delete(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 预约列表
     */
    @RequestMapping("/getAppointmentInfo")
    public R getAppointmentInfo(@RequestParam Map<String, Object> params) {
        PageUtils page = null;
        try {
            SysUserEntity user = this.getUser();
            Integer pageNuber = Integer.parseInt(params.get("page").toString());
            Integer pageSize = Integer.parseInt(params.get("limit").toString());
            page = studentService.getAppointmentInfo(user.getBusinessId(), pageNuber, pageSize, params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok().put("page", page);
    }


    /**
     * 校验是否老师登录，带出老师相关信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("/queryTeacherLogin")
    public Map<String, Object> queryTeacherLogin(Integer userId) {
        TeacherEntity teacherEntity = null;
        try {
            SysUserEntity user = this.getUser();
            //2:店长 3:教练
            if(user.getType()==2 || user.getType()==3){
                Long teacherId = user.getParentTeacherId();
                teacherEntity = teacherService.getById(teacherId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("teacherInfo", teacherEntity);
    }

    /**
     * 获取机构下所有店铺信息
     *
     * @param shopId
     * @return
     */
    @RequestMapping("/getShopInfo")
    public R getShopInfo(Integer shopId) {
        SysUserEntity user = this.getUser();
        List<ShopEntity> list = new ArrayList<>();
        try {
            int type = user.getType();
            //1机构  2店长 3教练
            if(type==1){
                ShopEntity optionDefault = new ShopEntity();
                optionDefault.setShopName("全部");
                list.add(optionDefault);
            }else if(type==2 || type==3){
                Long teacherId = user.getParentTeacherId();
                TeacherEntity teacherEntity = teacherService.getById(teacherId);
                shopId = teacherEntity.getShopId();
            }else if(type==4){
                Long parentId = user.getParentTeacherId();
                ParentEntity parentEntity = parentService.getById(parentId);
                shopId = parentEntity.getShopId();
            }
            list.addAll(studentService.getShopInfo(user.getBusinessId(), shopId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("list", list);
    }

    /**
     * 查询后台签到的老师
     *
     * @return
     */
    @RequestMapping("/getTeacher")
    public R getTeacher(int shopid) {
        Map<String, Object> map = new HashMap<>();
        map.put("shop_id", shopid);
        List<TeacherEntity> teacherEntityList = teacherService.listByMap(map);
        return R.ok().put("teacherEntityList", teacherEntityList);
    }

    /**
     * 查询所选课程课程
     *
     * @return
     */
    @RequestMapping("/getOneCourse")
    public R getOneCourse(int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("student_id", id);
        List<CourseStudentEntity> courseEntityList = courseStudentService.listByMap(map);
        CourseStudentEntity courseStudentEntity = courseEntityList.get(0);
        return R.ok().put("courseStudentEntity", courseStudentEntity);
    }

    /**
     * 查询可选所有课程
     *
     * @return
     */
    @RequestMapping("/getCourse")
    public R getCourse(String shopid) {
        Map<String, Object> map = new HashMap<>();
        map.put("shop_id", shopid);
        List<CourseEntity> courseEntityList = courseService.listByMap(map);
        return R.ok().put("courseEntityList", courseEntityList);
    }

    /**
     * 统计管理-学校人数统计
     * @param params
     * @return
     */
    @RequestMapping("/schoolCount/list")
    public R studentSchoolCountList(@RequestParam Map<String, Object> params) {
        PageUtils page = null;
        try {
            SysUserEntity user = this.getUser();
            params.put("organizeId", user.getBusinessId());
            page = studentService.queryPageStudentSchoolCount(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("page", page);
    }

    /**
     * 统计管理-地址人数统计
     * @param params
     * @return
     */
    @RequestMapping("/addressCount/list")
    public R studentAddressCountList(@RequestParam Map<String, Object> params) {
        PageUtils page = null;
        try {
            SysUserEntity user = this.getUser();
            params.put("organizeId", user.getBusinessId());
            page = studentService.queryPageStudentAddressCount(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("page", page);
    }

    /**
     * 统计管理-校区缴费统计
     * @param params
     * @return
     */
    @RequestMapping("/paymentSum/list")
    public R studentPaymentSumList(@RequestParam Map<String, Object> params) {
        PageUtils page = null;
        try {
            SysUserEntity user = this.getUser();
            params.put("organizeId", user.getBusinessId());
            page = studentService.queryPageStudenPaymentSum(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("page", page);
    }

    /**
     * 统计管理-消课率统计
     * @param params
     * @return
     */
    @RequestMapping("/classEeliminationRate/list")
    public R studentclassEeliminationRateList(@RequestParam Map<String, Object> params) {
        PageUtils page = null;
        try {
            SysUserEntity user = this.getUser();
            params.put("organizeId", user.getBusinessId());
            page = studentService.queryPageClassEeliminationRate(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("page", page);
    }

    /**
     * 订单管理-获取学生id
     */
    @RequestMapping("/getStudentList")
    public R getStudentList() {
        List<StudentEntity> list = studentService.list();
        return R.ok().put("list", list);
    }
    /**
     * 退费管理-根据订单获取学生
     */
    @RequestMapping("/getOrderStudent")
    public R getOrderStudent(Integer orderId) {
        CWOrderEntity cwOrderEntity = cwOrderService.getById(orderId);
        StudentEntity studentEntity = studentService.getById(cwOrderEntity.getStudentId());
        return R.ok().put("list", studentEntity);
    }


    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public R excelImport(@RequestParam(value="filename") MultipartFile file, HttpSession session){
        List<StudentManageEntity> list = null;
        try {
            //list = studentManageService.add(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(null != list && list.size() > 0){
            return R.ok().put("list",list);
        }else{
            return R.error("excel数据导入失败,请检查Excel表格数据是否正确。");
        }
    }

}
